<script lang="ts">
	import { page } from '$app/state';
	import { type InviteInfo } from '$lib/api/proto/roadmap_member_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { EllipsisVertical } from 'lucide-svelte';
	import moment from 'moment';

	interface Props {
		roadmapId: string;
	}
	let props: Props = $props();

	let inviteList = $state([] as InviteInfo[]);

	async function loadInviteList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapMemberApiClient.listInvite({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId
			}).response
		);
		inviteList = res.inviteList;
	}

	async function removeInvite(inviteCode: string) {
		if (userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.roadmapMemberApiClient.removeInvite({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				inviteCode: inviteCode
			}).response
		);
		const tmpList = inviteList.filter((item) => item.inviteCode != inviteCode);
		inviteList = tmpList;
		appStore.addToastMessage({
			level: 'info',
			content: '删除成功',
			keepTime: 2000
		});
	}

	$effect(() => {
		loadInviteList();
	});
</script>

<div class="overflow-x-auto pb-[100px]">
	<table class="table">
		<thead>
			<tr>
				<th>邀请码</th>
				<th>创建时间</th>
				<th>过期时间</th>
				<th class="w-[150px]">操作</th>
			</tr>
		</thead>
		<tbody>
			{#each inviteList as invite}
				<tr>
					<td>{invite.inviteCode}</td>
					<td>{moment(Number(invite.createTime)).format('YYYY-MM-DD HH:mm')}</td>
					<td class={Number(invite.expireTime) < moment().valueOf() ? 'text-error' : ''}
						>{moment(Number(invite.expireTime)).format('YYYY-MM-DD HH:mm')}</td
					>
					<td>
						<div class="flex gap-2">
							<button
								type="button"
								class="btn btn-ghost text-secondary p-1"
								onclick={() => {
									navigator.clipboard
										.writeText(
											`${page.url.protocol}//${page.url.host}/user/join?code=${invite.inviteCode}`
										)
										.then(() =>
											appStore.addToastMessage({
												level: 'info',
												content: '复制成功',
												keepTime: 2000
											})
										);
								}}>复制</button
							>
							<div class="dropdown">
								<div tabindex="0" role="button" class="btn btn-ghost">
									<EllipsisVertical size={16} />
								</div>
								<ul
									class="menu dropdown-content bg-base-100 rounded-box z-1 w-[80px] p-2 shadow-sm gap-2"
								>
									<li class="text-error">
										<button
											type="button"
											class="btn btn-ghost"
											onclick={() => removeInvite(invite.inviteCode)}>删除</button
										>
									</li>
								</ul>
							</div>
						</div>
					</td>
				</tr>
			{/each}
		</tbody>
	</table>
</div>
